// 无头单向非循环链表

#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

SLTNode* BuySListNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	newnode->data = x;
	newnode->next = NULL;

	return newnode;
}

void SListPushBack(SLTNode** ppHead, SLTDataType x)// 尾插
{
	SLTNode* newnode = BuySListNode(x);

	if (NULL == *ppHead)// 头结点判空

	{
		*ppHead = newnode;
	}
	else
	{
		SLTNode* tail = *ppHead;
		// 找到尾结点的指针
		while (tail->next != NULL)
		{
			tail = tail->next;
		}

		// 尾结点 链接 新结点
		tail->next = newnode;

	}
}

void SListPushFront(SLTNode** ppHead, SLTDataType x)// 头插
{
	SLTNode* newnode = BuySListNode(x);

	newnode->next = *ppHead;
	*ppHead = newnode;
}

void SListPophBack(SLTNode** ppHead)// 尾删
{
	if (NULL == *ppHead)// 链表为空
	{
		return;
	}
	else if(NULL == (*ppHead)->next)// 链表内只有一个结点
	{
		free(*ppHead);
		*ppHead = NULL;
	}
	else// 链表内不止一个结点
	{
		SLTNode* prev = NULL;
		SLTNode* tail = *ppHead;
		while (NULL != tail->next)
		{
			prev = tail;
			tail = tail->next;
		}

		free(tail);
		prev->next = NULL;

	}

}

void SListPopFront(SLTNode** ppHead)// 头删
{
	SLTNode* next = (*ppHead)->next;
	free(*ppHead);
	*ppHead = next;
}

SLTNode* SListFind(SLTNode* pHead, SLTDataType x)
{
	SLTNode* cur = pHead;

	while (cur)
	{
		if (x == cur->data)
		{
			return cur;
		}

		cur = cur->next;
	}

	return NULL;// 未找到相应元素的情况
}

void SListInsert(SLTNode** ppHead, SLTNode* pos, SLTDataType x)// 在pos的前面插入x
{

	if (pos == *ppHead)
	{
		SListPushFront(ppHead, x);
	}
	SLTNode* newnode = BuySListNode(x);
	SLTNode* prev = *ppHead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}

	prev->next = newnode;
	newnode->next = pos;
}

void SListErase(SLTNode** ppHead, SLTNode* pos)// 删除pos位置的值
{
	if (pos == *ppHead)
	{
		SListPopFront(ppHead);
	}
	else
	{
		SLTNode* prev = *ppHead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}

		prev->next = pos->next;
		free(pos);
	}
}

void SListPrint(SLTNode* pHead)// 打印
{
	SLTNode* cur = pHead;
	while (cur != NULL)
	{
		printf("%d -> ", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}